"""
完全使用selenium
"""
import time
from PIL import Image
from lxml import etree
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from myparse.chaojiying import parse_code

service = Service(executable_path="D:\\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.maximize_window()

page = 1
while True:
	driver.get(f"https://www.bjcourt.gov.cn/zxxx/indexOld.htm?st=1&zxxxlx=100013007&bzxrlx=&bzxrxm=&zrr=&frhqtzz=&jbfyId=&ah=&dqxh=22&page={page}")
	tree = etree.HTML(driver.page_source)
	items = tree.xpath('//table[@class="table_list_02"]//tr[position()>1]')
	if items:
		for item in items:
			print(item.xpath('./td/text()'))
		page += 1
		if page == 579:
			break
	else:
		input_ele = driver.find_element(By.ID, "yzmInput") # 获取验证码图片
		image_ele = driver.find_element(By.ID, "yzmImg") # 获取验证码图片
		submit_ele = driver.find_element(By.CSS_SELECTOR, ".login_bflmc span") # 获取提交按钮

		driver.save_screenshot("screen.png") # 截取整个屏幕
		screen = Image.open("screen.png") # 打开截图
		box = (image_ele.location["x"], image_ele.location["y"], image_ele.location["x"] + image_ele.rect["width"], image_ele.location["y"] + image_ele.rect["height"])
		rect = screen.crop(box) # 裁剪验证码图片
		rect.save("rect.png") # 保存验证码图片
		code = parse_code("rect.png", 1005) # 调用解析验证码的函数
		input_ele.send_keys(code) # 输入验证码
		time.sleep(2)
		submit_ele.click()


